﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;

namespace EPE.Common
{
    public class ApCommonModel
    {
        public static string GetAppUrlPath()
        {
            HttpContext wHC = HttpContext.Current;
            return wHC.Request.ApplicationPath;
        }
        public static string GetMapPathUrlPath(string argPath)
        {
            HttpContext wHC = HttpContext.Current;
            return wHC.Request.MapPath(argPath);
        }
        public static object ParamValue(object StrValue)
        {
            object objValue;
            if (StrValue == null)
            {
                objValue = DBNull.Value;
            }
            else
            {
                objValue = StrValue.ToString().Trim();
                if (objValue.ToString() == "")
                {
                    objValue = DBNull.Value;
                }
            }


            return objValue;

        }
        public static int SizeOfHZ(string StrValue)
        {
            System.Text.Encoding wEncodeSJIS = System.Text.Encoding.GetEncoding("GB2312");
            return wEncodeSJIS.GetByteCount(StrValue);
        }

        public int SizeOfSJIS(string StrValue)
        {
            System.Text.Encoding wEncodeSJIS = System.Text.Encoding.GetEncoding("Shift_JIS");
            return wEncodeSJIS.GetByteCount(StrValue);
        }

        public static DateTime GetFirstDayOfMonth(DateTime argDate)
        {
            return Convert.ToDateTime(argDate.Year + "/" + argDate.Month + "/1");
        }
        public static DateTime GetLastDayOfMonth(DateTime argDate)
        {
            return Convert.ToDateTime(argDate.Year + "/" + argDate.Month + "/" + System.DateTime.DaysInMonth(argDate.Year, argDate.Month));
        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="response"></param>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        public static void FileDownLoad(HttpResponse response, string filePath, string fileName)
        {
            string tempfilePath = filePath;
            FileInfo file = new FileInfo(tempfilePath);
            response.Clear();
            response.ClearHeaders();
            response.Buffer = false;

            response.ContentEncoding = System.Text.Encoding.Default;
            response.ContentType = "application/octet-stream";

            response.AddHeader("Content-Disposition", "attachment; filename=" + HttpContext.Current.Server.UrlEncode(fileName));
            if (file.Exists)
            {
                response.AddHeader("Content-Length", file.Length.ToString());
                response.WriteFile(file.FullName);
                response.Flush();
                response.End();
            }
        }

        public static double BothTimeDifferenceOfDay(string argStartTime, string argEndTime)
        {
            try
            {

                DateTime aStartTime = Convert.ToDateTime(argStartTime);
                DateTime aEndTime = Convert.ToDateTime(argEndTime);

                TimeSpan dTime = aEndTime.Subtract(aStartTime);

                return dTime.TotalDays;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        public static double BothTimeDifferenceOfSeconds(string argStartTime, string argEndTime)
        {
            try
            {

                DateTime aStartTime = Convert.ToDateTime(argStartTime);
                DateTime aEndTime = Convert.ToDateTime(argEndTime);

                TimeSpan dTime = aEndTime.Subtract(aStartTime);

                return dTime.TotalSeconds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static double BothTimeDifferenceOfHour(string argStartTime, string argEndTime)
        {
            try
            {

                DateTime aStartTime = Convert.ToDateTime(argStartTime);
                DateTime aEndTime = Convert.ToDateTime(argEndTime);

                TimeSpan dTime = aEndTime.Subtract(aStartTime);

                return dTime.TotalHours;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static double BothTimeDifferenceOfMinute(string argStartTime, string argEndTime)
        {
            try
            {

                DateTime aStartTime = Convert.ToDateTime(argStartTime);
                DateTime aEndTime = Convert.ToDateTime(argEndTime);

                TimeSpan dTime = aEndTime.Subtract(aStartTime);

                return dTime.TotalMinutes;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static int Weekday(DateTime argDate)
        {
            int rtnDay = 0;
            if (argDate.DayOfWeek == DayOfWeek.Sunday)
            {
                rtnDay = 1;
            }
            else if (argDate.DayOfWeek == DayOfWeek.Monday)
            {
                rtnDay = 2;
            }
            else if (argDate.DayOfWeek == DayOfWeek.Tuesday)
            {
                rtnDay = 3;
            }
            else if (argDate.DayOfWeek == DayOfWeek.Wednesday)
            {
                rtnDay = 4;
            }
            else if (argDate.DayOfWeek == DayOfWeek.Thursday)
            {
                rtnDay = 5;
            }
            else if (argDate.DayOfWeek == DayOfWeek.Friday)
            {
                rtnDay = 6;
            }
            else if (argDate.DayOfWeek == DayOfWeek.Saturday)
            {
                rtnDay = 7;
            }

            return rtnDay;

        }

        public static string HtmlTrans(string strTxt)
        {
            string repTxt;
            repTxt = Convert.ToString(strTxt);
            if (repTxt != "")
            {
                repTxt = repTxt.Replace("&", "&amp;");
                repTxt = repTxt.Replace("<", "&lt;");
                repTxt = repTxt.Replace(">", "&gt;");
                repTxt = repTxt.Replace("\"", "&quot;");
                repTxt = repTxt.Replace("'", "&#39;");
            }
            return repTxt;
        }

        public static string NullToZero(string argSource)
        {
            string sNum = argSource.Trim();
            if (sNum == string.Empty)
            {
                return "0";
            }
            return sNum;
        }

        #region "GetFileExtension"
        /// <summary>
        /// 根据指定的文件，取得其扩展名。
        /// </summary>
        /// <param name="argFileName"></param>
        /// <returns></returns>
        public static string GetFileExtension(string argFileName)
        {
            int iLastIndex = argFileName.LastIndexOf(".");
            string sResult = argFileName.Substring(iLastIndex + 1);
            return sResult.ToLower();
        }
        #endregion

        #region"save file to server"
        /// <summary>
        /// 将文件上传到服务器，并返路径和文件名
        /// </summary>
        /// <param name="PostFile"></param>
        /// <param name="argPrefix"></param>
        /// <returns></returns>
        public static string PostDataToFile(HttpPostedFile PostFile, string argPrefix)
        {
            AppSettingsReader wASR = new AppSettingsReader();
            string strTempUrl;
            Guid clsGuid = Guid.NewGuid();
            string strGuid = clsGuid.ToString();
            string strTempFilePath;
            string strTempFileName;
            string strtmp;

            try
            {


                strTempUrl = GetAppUrlPath() + wASR.GetValue("FileUploadPath", typeof(string)).ToString();
                strTempFilePath = GetMapPathUrlPath(strTempUrl);
                //argFilePath = strTempFilePath;

                strTempFileName = System.IO.Path.GetFileName(PostFile.FileName);

                strtmp = System.DateTime.Now.ToShortDateString().Replace("/", "").Replace(":", "").Replace("-", "").Trim();
                strTempFileName = argPrefix + strtmp + "_" + strGuid.ToString() + "_" + strTempFileName;

                //argFileName = strTempFileName;
                strTempFileName = System.IO.Path.Combine(strTempFilePath, strTempFileName);

                PostFile.SaveAs(strTempFileName);

                return strTempFileName;
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region "通过身份证算出年龄"
        /// <summary>
        /// 通过身份证算出年龄
        /// </summary>
        /// <param name="argIDCard"></param>
        /// <returns></returns>
        public static string GetAge(string argIDCard)
        {
            string strBirthday = string.Empty;
            string strAge = string.Empty;
            if (argIDCard.Length == 15)
            {
                strBirthday = "19" + argIDCard.Substring(6, 6);
            }
            else if (argIDCard.Length == 18)
            {
                strBirthday = argIDCard.Substring(6, 8);
            }
            if (strBirthday != string.Empty)
            {

                DateTime dtBirthday = DateTime.ParseExact(
                    strBirthday, "yyyyMMdd", null);
                if (DateTime.Now.Month < dtBirthday.Month
                    || (DateTime.Now.Month == dtBirthday.Month
                    && DateTime.Now.Day < dtBirthday.Day))
                {
                    strAge = Convert.ToString(
                        DateTime.Now.Year - dtBirthday.Year - 1);
                }
                else
                {
                    strAge = Convert.ToString(
                        DateTime.Now.Year - dtBirthday.Year);
                }
            }
            return strAge;
        }
        #endregion

        #region "通过身份证算出出生日"
        /// <summary>
        /// 通过身份证算出出生日
        /// </summary>
        /// <param name="argIDCard"></param>
        /// <returns></returns>
        public static string GetBirthday(string argIDCard)
        {
            string strBirthday = string.Empty;
            string strAge = string.Empty;
            if (argIDCard.Length == 15)
            {
                strBirthday = "19" + argIDCard.Substring(6, 6);
            }
            else if (argIDCard.Length == 18)
            {
                strBirthday = argIDCard.Substring(6, 8);
            }
            DateTime dtBirthday = DateTime.ParseExact(
                    strBirthday, "yyyyMMdd", null);

            return dtBirthday.ToShortDateString();
        }
        #endregion


        #region""

        /// <summary>
        /// 排序方式
        /// </summary>
        public enum SortKind
        {
            /// <summary>
            /// 升序
            /// </summary>
            ASC = 0,
            /// <summary>
            /// 降序
            /// </summary>
            DESC
        }


        /// <summary>
        /// 将实体对象集合按字段排序
        /// </summary>
        /// <typeparam name="T">实体对象类型</typeparam>
        /// <param name="list">实体对象集合</param>
        /// <param name="field">排序字段</param>
        /// <param name="kind">排序方式</param>
        /// <returns>排序后的集合</returns>
        public static List<T> Sort<T>(List<T> list, string field, SortKind kind)
        {
            if (list != null)
            {
                switch (kind)
                {
                    case SortKind.ASC: list = list.OrderBy(t => GetValue(t, field)).ToList(); break;
                    case SortKind.DESC: list = list.OrderByDescending(t => GetValue(t, field)).ToList(); break;
                }
            }
            return list;
        }

        /// <summary>
        /// 动态获取如model对象中的XX对象的XX属性
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        private static object GetValue<T>(T model, string field)
        {
            if (field.Split('.').Length == 1)
                return model.GetType().GetProperty(field).GetValue(model, null);

            int index = field.IndexOf('.');
            string f1 = field.Substring(0, index);
            string f2 = field.Substring(index + 1);
            object obj = model.GetType().GetProperty(f1).GetValue(model, null);
            return GetValue(obj, f2);
        }
        #endregion


        #region "des加密字符串"
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string EncryptString(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }
        #endregion

        #region "des解密字符串"
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string DecryptString(string decryptString, string decryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
                byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }

        #endregion

        #region "MD5加密"
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">加密字符</param>
        /// <param name="code">加密位数16/32</param>
        /// <returns></returns>
        public static string md5(string str, int code)
        {
            if (string.IsNullOrEmpty(str))
            {
                return string.Empty;
            }
            string strEncrypt = string.Empty;
            if (code == 16)
            {
                strEncrypt = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").Substring(8, 16);
            }

            if (code == 32)
            {
                strEncrypt = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
            }

            return strEncrypt;
        }
        #endregion

        /// <summary>
        /// 将图片缩小
        /// </summary>
        /// <param name="strOldPic"></param>
        /// <param name="strNewPic"></param>
        /// <param name="intWidth"></param>
        /// <param name="intHeight"></param>
        public static void SmallPic(string strOldPic, string strNewPic, int intWidth, int intHeight)
        {
            System.Drawing.Bitmap objPic, objNewPic;
            try
            {
                objPic = new System.Drawing.Bitmap(strOldPic);
                objNewPic = new System.Drawing.Bitmap(objPic, intWidth, intHeight);
                objNewPic.Save(strNewPic);
            }
            catch (Exception exp)
            { throw exp; }
            finally
            {
                objPic = null;
                objNewPic = null;
            }
        }

        public static string ConvertToAsscii(string argInput)
        {
            string strOut = string.Empty;

            if (argInput.Length > 0)
            {
                for (int i = 0; i < argInput.Length; i++)
                {
                    string strTemp = argInput[i].ToString();
                    ASCIIEncoding asc = new ASCIIEncoding();

                    int intAsciiCode = (int)asc.GetBytes(strTemp)[0];

                    strOut = strOut + intAsciiCode;

                }
            }

            return strOut;
        }


        #region "3des加密字符串"
        /// <summary>
        /// 3DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string TripleDESEncryptString(string encryptString)
        {
            string strOut = string.Empty;
            try
            {
                //byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.PadLeft(24,'0').Substring(0, 24));
                //byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                TripleDESCryptoServiceProvider dCSP = new TripleDESCryptoServiceProvider();

                dCSP.GenerateKey();
                dCSP.GenerateIV();

                byte[] rgbKey = dCSP.Key;
                byte[] rgbIV = dCSP.IV;
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                strOut = Convert.ToBase64String(mStream.ToArray());

                string strKey = Convert.ToBase64String(rgbKey);
                string strIv = Convert.ToBase64String(rgbIV);

                strOut = strOut + "$" + strKey + "$" + strIv;

                return strOut;
            }
            catch (Exception ex)
            {
                return encryptString;
            }
        }
        #endregion

        #region "3des解密字符串"
        /// <summary>
        /// 3DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为16位或24位,和加密密钥相同</param>
        /// <param name="decryptIv">解密向量,要求为8位,和加密向量相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string TripleDESDecryptString(string decryptString, string decryptKey, string decryptIv)
        {
            try
            {
                byte[] rgbKey = Convert.FromBase64String(decryptKey);
                byte[] rgbIV = Convert.FromBase64String(decryptIv);
                byte[] inputByteArray = Convert.FromBase64String(decryptString);

                TripleDESCryptoServiceProvider DCSP = new TripleDESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch (Exception ex)
            {
                return decryptString;
            }
        }

        #endregion


        /// <summary>
        /// 读取Excel至DataSet
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static DataSet LoadExcel(string filePath)
        {
            return LoadExcel(filePath, "*");
        }
        public static DataSet LoadExcel(string filePath, string colsName)
        {
            DataSet ds = new DataSet("data");
            if (string.IsNullOrEmpty(filePath))
            {
                return ds;
            }
            string strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0; HDR=YES; IMEX=1'", filePath);
            //string strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", filePath);

            OleDbConnection objConn = new OleDbConnection(strConn);
            objConn.Open();
            DataTable schemaTable = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            OleDbDataAdapter sqlada = new OleDbDataAdapter();
            foreach (DataRow dr in schemaTable.Rows)
            {
                try
                {
                    string strSql = string.Format("Select {0} From [{1}]", colsName, dr[2].ToString().Trim());
                    OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
                    sqlada.SelectCommand = objCmd;
                    sqlada.Fill(ds, dr[2].ToString().Trim());
                }
                catch
                {
                }
            }
            objConn.Close();
            return ds;
        }

        public static string GetYearMonth(string argPara)
        {
            string rtnData;
            if (InputChecker.CheckDateTime(argPara))
            {
                rtnData = Convert.ToDateTime(argPara).Year.ToString() + "-" + Convert.ToDateTime(argPara).Month.ToString().PadLeft(2, '0');
            }
            else
            {
                rtnData = argPara;
            }

            return rtnData;
        }

        public static string GetIp()
        {
            string result = "";
            if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
            {
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            return result;
        }

        ///   <summary> 
        ///   绑定生成一个有树结构的下拉菜单 
        ///   </summary> 
        ///   <param   name="dtNodeSets">菜单记录数据所在的表</param> 
        ///   <param   name="strParentColumn">表中用于标记父记录的字段</param> 
        ///   <param   name="strRootValue">第一层记录的父记录值(通常设计为0或者-1或者Null)用来表示没有父记录</param> 
        ///   <param   name="strIndexColumn">索引字段，也就是放在DropDownList的Value里面的字段</param> 
        ///   <param   name="strTextColumn">显示文本字段，也就是放在DropDownList的Text里面的字段</param> 
        ///   <param   name="drpBind">需要绑定的DropDownList</param> 
        ///   <param   name="i">用来控制缩入量的值，请输入-1</param> 
        public static void MakeTree(DataTable dtNodeSets, string strParentColumn, string strRootValue, string strIndexColumn, string strTextColumn, DropDownList drpBind, int i)
        {
            //每向下一层，多一个缩入单位 
            i++;
            DataView dvNodeSets = new DataView(dtNodeSets);
            dvNodeSets.RowFilter = strParentColumn + "='" + strRootValue + "'";
            string strPading = "";     //缩入字符 
            //通过i来控制缩入字符的长度，我这里设定的是一个全角的空格 
            for (int j = 0; j < i; j++)
                strPading += "　";//如果要增加缩入的长度，改成两个全角的空格就可以了 
            foreach (DataRowView drv in dvNodeSets)
            {
                TreeNode tnNode = new TreeNode();
                ListItem li = new ListItem(strPading + "├" + drv[strTextColumn].ToString(), drv[strIndexColumn].ToString());
                drpBind.Items.Add(li);
                MakeTree(dtNodeSets, strParentColumn, drv[strIndexColumn].ToString(), strIndexColumn, strTextColumn, drpBind, i);
            }
            //递归结束，要回到上一层，所以缩入量减少一个单位 
            i--;
        }
    }
}
